import session from '@/store/reducers/session';
import React, { useEffect, useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import FileMessage from './FileMessage';
import { getCustomerInfo, sendMessageToRecord } from '@/utils';
import { setChatRecord } from '@/store/reducers/chatRecord';
import UserJoinSession from './UserJoinSession';
import Time from './Time';
import Preview from '@/components/Preview';
import WidgetEmoji from '@/utils/Emoji';
import { useTranslation } from 'react-i18next';

interface ChatMessageProps {
	name?: string;
	message?: string;
	fromRole?: string;
	msgType?: string;
}

const ChatMessage = (props: ChatMessageProps) => {
	const { t } = useTranslation();
	const dispatch = useDispatch();
	const { name, message, fromRole, msgType } = props;
	//perview组件显示与隐藏
	const [isShowPreview, setIsShowPreview] = useState<boolean>(false);
	//图片url
	const [imgUrl, setImgUrl] = useState<string>('');

	const [startMsgTime, setStartMsgTime] = useState(0);

	const { chatRecord, agent, newMessage, session } = useSelector(state => state) as any;
	const chatListRef = useRef(null);
	//监听消息滑动至最底部
	useEffect(() => {
		const current: any = chatListRef.current!;
		current.scrollTop = current.scrollHeight;
		if (chatRecord.length === 0) {
			setIsShowPreview(false);
		}
	}, [chatRecord]);

	//监听访客发送文本消息
	useEffect(() => {
		console.log(newMessage);

		if (JSON.stringify(newMessage) !== '{}') {
			let customer = getCustomerInfo(newMessage.from, session.members);
			let data = null;
			switch (newMessage.type) {
				case 'text':
					//文字
					data = sendMessageToRecord('text', WidgetEmoji.textFace2imgFace(newMessage.data), customer);
					break;
				case 'link':
					//图片
					data = sendMessageToRecord('link', newMessage.data, customer);
					break;
				default:
					break;
			}
			dispatch(setChatRecord(data));
		}
	}, [newMessage]);

	const getMessageType = (item: any, type: string) => {
		let message = null;
		switch (type) {
			case 'text':
				message = <p dangerouslySetInnerHTML={{ __html: item.data }}></p>;
				break;
			case 'link':
				if (item.data.type === 'pic') {
					message = (
						<img
							src={item.data.url}
							alt=""
							width="200px"
							onClick={() => {
								setImgUrl(item.data.url);
								setIsShowPreview(true);
							}}
						/>
					);
				} else if (item.data.type === 'doc') {
					message = <FileMessage type={item.data.suffix} fileName={item.data.name} fileUrl={item.data.url} onClick={downFile} />;
				}
				break;
			default:
				break;
		}
		return message;
	};

	//下载文件
	const downFile = async (fileUrl: string, fileName: string) => {
		let src = fileUrl.replace(/^(http:\/\/)/, 'https://');
		let response = await fetch(src); // 内容转变成blob地址
		let blob = await response.blob(); // 创建隐藏的可下载链接
		let objectUrl = window.URL.createObjectURL(blob);
		let a = document.createElement('a');
		a.href = objectUrl;
		a.download = fileName;
		a.click();
		a.remove();
	};

	return (
		<div className="chat-message-container" ref={chatListRef}>
			{chatRecord.map((item: any, index: any) => {
				if (item.label === 'agent' && item.fromUser.name === agent.userName) {
					return (
						<div key={index}>
							{item.showTime ? <Time /> : undefined}
							<div className="agent-box">
								<div className="agent-message">
									<p className="agent-name">{t('agent') + item.fromUser.name}</p>
									<div className="text">{getMessageType(item, item.type)}</div>
								</div>
							</div>
						</div>
					);
				} else if (item.label !== 'system') {
					return (
						<div key={index}>
							{item.showTime ? <Time /> : undefined}
							<div className="client-box">
								<div className="client-message">
									<p className="client-name">{`${item.label === 'customer' ? '' : t('agent')} ` + item.fromUser.name}</p>
									<div className="text">{getMessageType(item, item.type)}</div>
								</div>
							</div>
						</div>
					);
				} else if (item.label === 'system') {
					return (
						<div key={index}>
							<Time />
							<UserJoinSession message={item.data} />
						</div>
					);
				}
			})}
			{isShowPreview ? (
				<Preview
					imgUrl={imgUrl}
					onClick={() => {
						setIsShowPreview(false);
					}}
				/>
			) : undefined}
		</div>
	);
};

export default ChatMessage;
